//
//  LocationViewController.m
//  百度地图
//
//  Created by ljm on 2017/7/6.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "LocationViewController.h"

@interface LocationViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>

{
    BMKMapView * _myMapView;
    BMKLocationService * _locationServer;
    BMKPointAnnotation *_myPointAnnotation;
    
    BMKUserLocation *_userLocation;
    BMKPointAnnotation *pointAnnotation;
    
    CLGeocoder *_geocoder;
    
}

@end

@implementation LocationViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    _myMapView.delegate = self;
    _locationServer.delegate = self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"定位";
    
    _myMapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64)];
    _locationServer = [[BMKLocationService alloc] init];
    _myPointAnnotation = [[BMKPointAnnotation alloc] init];
    
//    [_myMapView setMapType:BMKMapTypeStandard];
    _myMapView.mapType = BMKMapTypeSatellite;
    [_myMapView setTrafficEnabled:YES];
//    [_myMapView setBaiduHeatMapEnabled:YES];
    _geocoder = [[CLGeocoder alloc] init];
    
    [self.view addSubview:_myMapView];
    
    [self setupUI];
    
    
    /**
     *    长按手势添加大头针
     */
    UILongPressGestureRecognizer *tapGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureClicked:)];
    [_myMapView addGestureRecognizer:tapGesture];
    
    
}


#pragma mark -- 相应长按手势
- (void) tapGestureClicked :(UILongPressGestureRecognizer*) gesture
{
    /** 长按手势结束 **/
    if (gesture.state == UIGestureRecognizerStateEnded) {
        
        /** 获取当前坐标的点 **/
        CGPoint currentPoint = [gesture locationInView:_myMapView];
        
        /** 根据坐标转换为经纬度 **/
        CLLocationCoordinate2D pt = [_myMapView convertPoint:currentPoint toCoordinateFromView:_myMapView];
        
        NSLog(@"%f,%f",pt.latitude,pt.longitude);
        
        /** 将经纬度转换为地址 **/
        CLLocation *currentLoction = [[CLLocation alloc] initWithLatitude:pt.latitude longitude:pt.longitude];
        
        [_geocoder reverseGeocodeLocation:currentLoction completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
           
            NSArray *addressListArray = placemarks.lastObject.addressDictionary[@"FormattedAddressLines"];
            NSLog(@"%@",addressListArray.firstObject);
            
            NSString *addressListArr = addressListArray.firstObject;
            NSLog(@"%@",addressListArr);
            
            //设置经纬度
            _myPointAnnotation.coordinate = pt;
            _myPointAnnotation.title = addressListArr;
            _myPointAnnotation.subtitle = @"i am comming";
            //添加大头针
            [_myMapView addAnnotation:_myPointAnnotation];
            
            [_myMapView selectAnnotation:_myPointAnnotation animated:YES];
            
        }];
        
    }
}

#pragma mark -- 设置按钮
- (void) setupUI
{
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"跟随定位" style:UIBarButtonItemStylePlain target:self action:@selector(startFllow)];
    self.navigationItem.rightBarButtonItem = rightBtn;
    
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithTitle:@"罗盘定位" style:UIBarButtonItemStylePlain target:self action:@selector(startLocation)];
    self.navigationItem.leftBarButtonItem = leftBtn;
    
}

#pragma mark -- 设置大头针
- (void)setupAnnotation
{
    _myMapView.centerCoordinate = _userLocation.location.coordinate;//（如果直接写在代理方法中，需要在代理方法末尾调用[_locService stopUserLocationService] 方法，让定位停止，要不然一直定位，你的地图就一直锁定在一个位置）。
    _myPointAnnotation = [[BMKPointAnnotation alloc] init];
    _myPointAnnotation.coordinate = _userLocation.location.coordinate;
    _myPointAnnotation.title = pointAnnotation.title;//@"我在这里";
    _myPointAnnotation.subtitle = pointAnnotation.title;
    
    [_myMapView addAnnotation:_myPointAnnotation];
    [_myMapView selectAnnotation:_myPointAnnotation animated:YES];
}


#pragma mark -- 跟随定位
- (void)startFllow
{
    
    /// 地图比例尺级别，在手机上当前可使用的级别为3-21级
    /**
     *    
     3级最大，全球可见
     21级最小、最详细
     */
    
    [_myMapView setZoomLevel:12];
    /** 启动 **/
    [_locationServer startUserLocationService];
    
    _myMapView.showsUserLocation = NO;
    _myMapView.userTrackingMode = BMKUserTrackingModeFollow;
    _myMapView.showsUserLocation = YES;
}

#pragma mark -- 罗盘定位
- (void)startLocation
{
    [_myMapView setZoomLevel:15];
    /** 启动 **/
    [_locationServer startUserLocationService];
    
    _myMapView.showsUserLocation = NO;
    _myMapView.userTrackingMode = BMKUserTrackingModeFollowWithHeading;
    _myMapView.showsUserLocation = YES;
}

#pragma mark -- 方向变更
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    NSLog(@"方向变更%@",userLocation.heading);
    [_myMapView updateLocationData:userLocation];
    _userLocation = userLocation;
    
    [self setupAnnotation];
    [_locationServer stopUserLocationService];
}


#pragma mark -- 位置变更
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"位置变更%f,%f",userLocation.location.coordinate.longitude,userLocation.location.coordinate.latitude);
    [_myMapView updateLocationData:userLocation];
    
}

#pragma mark -- 反向地理编码获取地址
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == 0) {
        pointAnnotation = [[BMKPointAnnotation alloc] init];
        pointAnnotation.coordinate = result.location;
        pointAnnotation.title = result.address;
        NSLog(@"%@",pointAnnotation.title);
        NSLog(@"%f,%f",pointAnnotation.coordinate.longitude,pointAnnotation.coordinate.latitude);
    }
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    _locationServer.delegate = nil;
    _myMapView.delegate = nil;
}

@end
